﻿var roomVars = new Array();
var foodInGame = 20;
var zone;
var room;
var MAX_PLAYERS;
var gameStatus;

function init()
{
        // Using trace will send data to the server console
//        trace("Hello from the Simple Extension Example!")
	zone = _server.getCurrentZone();
	room = zone.getRoomByName("The Hall");
	MAX_PLAYERS = room.getMaxUsers();
	initializeRoom();
}

function destroy()
{
        trace("Bye bye!")
}

function handleRequest(cmd, params, user, fromRoom)
{
	var response = { }
	var uList = room.getAllUsers()

	if (cmd == "crtfood")//create food
    {
		response._cmd = "crtfood";
		response.roomVariables = roomVars;

    	_server.sendResponse(response ,-1, null, uList);
	}
	if (cmd == "addblue")
    {
			roomVars[(foodInGame * 2)].val++;
            response._cmd = "addblue"
			response.roomVariables = roomVars;
            _server.sendResponse(response , -1, null, uList)
	}
	if (cmd == "addred")
    {
			roomVars[(foodInGame * 2)+1].val++;
            response._cmd = "red_points"
			response.roomVariables = roomVars;
            _server.sendResponse(response ,-1, null, uList)
	}
	if (cmd == "mvfood")//move food
    {
			var vars = params.vars;
			var foodIndex = Number(vars[2].val);
			roomVars[2 * (foodIndex - 1)].val = vars[0].val;
			roomVars[2 * (foodIndex - 1)+1].val = vars[1].val;

            response._cmd = "mvfood"
			response.roomVariables = roomVars;
            _server.sendResponse(response ,-1, null, uList)
	}
	if (cmd == "getupd")//get update
    {
            response._cmd = "getupd"
			response.roomVariables = roomVars;
            _server.sendResponse(response ,-1, null, uList)
	}
}

function handleInternalEvent(evt)
{
    var uList = room.getAllUsers();
	
	if (evt.name == "userJoin")
	{
		if(uList.length == MAX_PLAYERS){
			
		} else {
			
		}
	}
	if (evt.name == "userExit" || evt.name == "logOut" || evt.name == "userLost")
	{
		trace(uList.length);
		if((uList.length -1) == 0){
			trace("initializing room");
			initializeRoom();
		}
	}
}

function initializeRoom(){
	
	roomVars = new Array();
	gameStatus = 0;
	
	for(i=1;i<(foodInGame+1);i++){
			var foodX = Number(Math.random()*(2000));
			var foodY = Number(Math.random()*(2000));
				
			roomVars.push({name:"food_x_"+i, val:foodX})
			roomVars.push( { name:"food_y_" + i, val:foodY } )
					
		}
			
	roomVars.push( {name:"blue_points", val:0} );
	roomVars.push( {name:"red_points", val:0} );  
	roomVars.push( {name:"game_status", val:gameStatus} );
}